package cn.walls1717.ggkt.vod.service.impl;

import cn.walls1717.ggkt.model.vod.Course;
import cn.walls1717.ggkt.model.vod.CourseDescription;
import cn.walls1717.ggkt.model.vod.Subject;
import cn.walls1717.ggkt.model.vod.Teacher;
import cn.walls1717.ggkt.vo.vod.*;
import cn.walls1717.ggkt.vod.mapper.CourseMapper;
import cn.walls1717.ggkt.vod.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程服务实现类
 *
 * @author walls1717
 * @since 2022/07/14
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SubjectService subjectService;
    @Autowired
    private CourseDescriptionService courseDescriptionService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private VideoService videoService;

    /**
     * 点播课程列表
     */
    @Override
    public Page<Course> listPages(Integer pageNum, Integer pageSize, CourseQueryVo courseQueryVo) {
        Page<Course> coursePage = new Page<>(pageNum, pageSize);
        // 名称
        String title = courseQueryVo.getTitle();
        // 二级分类
        Long subjectId = courseQueryVo.getSubjectId();
        // 一级分类
        Long subjectParentId = courseQueryVo.getSubjectParentId();
        // 讲师
        Long teacherId = courseQueryVo.getTeacherId();
        LambdaQueryWrapper<Course> lqw = new LambdaQueryWrapper<>();
        // 判断是否有查询条件，有查询条件拼接查询条件
        if (!StringUtils.isEmpty(title)) {
            lqw.like(Course::getTitle, title);
        }
        if (!StringUtils.isEmpty(subjectId)) {
            lqw.eq(Course::getSubjectId, subjectId);
        }
        if (!StringUtils.isEmpty(subjectParentId)) {
            lqw.eq(Course::getSubjectParentId, subjectParentId);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            lqw.eq(Course::getTeacherId, teacherId);
        }
        // 根据查询条件分页查询
        this.page(coursePage, lqw);
        List<Course> records = coursePage.getRecords();
        // 对分页查询的数据进行处理，添加讲师姓名以及分类名称
        records.forEach(this::getTeacherOrSubjectName);
        coursePage.setRecords(records);
        return coursePage;
    }

    /**
     * 保存或修改课程信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveOrUpdateCourseInfo(CourseFormVo courseFormVo) {
        // 先保存课程章节信息
        Course course = new Course();
        BeanUtils.copyProperties(courseFormVo, course);
        this.saveOrUpdate(course);

        // 再保存课程简介信息
        Long id = course.getId();
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setDescription(courseFormVo.getDescription());
        courseDescription.setId(id);
        courseDescriptionService.saveOrUpdate(courseDescription);
        return id;
    }

    /**
     * 根据id查询课程消息
     */
    @Override
    public CourseFormVo getCourseById(Long id) {
        // 根据id查询到课程信息
        Course course = this.getById(id);
        if (course == null) {
            return null;
        }
        // 根据id查询到课程描述信息
        CourseDescription courseDescription = courseDescriptionService.getById(id);
        CourseFormVo courseFormVo = new CourseFormVo();
        // 将course数据拷贝到courseFormVo中
        BeanUtils.copyProperties(course, courseFormVo);
        // 为courseFormVo设置描述信息
        if (courseDescription != null) {
            courseFormVo.setDescription(courseDescription.getDescription());
        }
        return courseFormVo;
    }

    /**
     * 根据id获取课程发布信息
     */
    @Override
    public CoursePublishVo getCoursePublishVoById(Long id) {
        return baseMapper.selectCoursePublishVo(id);
    }

    /**
     * 根据id发布课程
     */
    @Override
    public void updatePublishStatusById(Long id) {
        Course course = this.getById(id);
        // 状态1为已发布
        course.setStatus(1);
        // 设置发布时间为当前时间
        course.setPublishTime(new Date());
        this.updateById(course);
    }

    /**
     * 删除课程
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCourse(Long id) {
        // 删除课程信息
        this.removeById(id);
        // 删除课程简介信息，这里课程简介id和课程id为对应关系，直接删除即可
        courseDescriptionService.removeById(id);
        // 删除章节信息
        chapterService.removeByCourseId(id);
        // 删除小节信息
        videoService.removeByCourseId(id);
    }

    /**
     * 根据课程id查询课程详情
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> getCourseInfoById(Long courseId) {
        //更新流量量
        Course course = this.getById(courseId);
        course.setViewCount(course.getViewCount() + 1);
        this.updateById(course);

        Map<String, Object> map = new HashMap<>();
        CourseVo courseVo = baseMapper.selectCourseVoById(courseId);
        List<ChapterVo> chapterVoList = chapterService.listTree(courseId);
        CourseDescription courseDescription = courseDescriptionService.getById(courseId);
        Teacher teacher = teacherService.getById(course.getTeacherId());

        // TODO 后续完善
        Boolean isBuy = false;

        map.put("courseVo", courseVo);
        map.put("chapterVoList", chapterVoList);
        map.put("description", null != courseDescription ?
                courseDescription.getDescription() : "");
        map.put("teacher", teacher);
        //是否购买
        map.put("isBuy", isBuy);
        return map;
    }

    /**
     * 获取讲师和分类名称
     */
    private void getTeacherOrSubjectName(Course course) {
        //查询讲师名称
        Teacher teacher = teacherService.getById(course.getTeacherId());
        if (teacher != null) {
            course.getParam().put("teacherName", teacher.getName());
        }
        //查询分类名称
        Subject subjectOne = subjectService.getById(course.getSubjectParentId());
        if (subjectOne != null) {
            course.getParam().put("subjectParentTitle", subjectOne.getTitle());
        }
        Subject subjectTwo = subjectService.getById(course.getSubjectId());
        if (subjectTwo != null) {
            course.getParam().put("subjectTitle", subjectTwo.getTitle());
        }
    }

    /**
     * 查询所有课程
     */
    @Override
    public List<Course> listCourses() {
        List<Course> courseList = this.list();
        courseList.forEach(this::getTeacherOrSubjectName);
        return courseList;
    }
}
